package com.hust360.percent.pojo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.pojo.Brand.BrandDAO;

public class BrandDAOImpl implements BrandDAO {

	@Override
	public Brand findById(Long id) {
		Brand brand = null;
		Cursor c = PercentApplication.localDB
				.rawQuery("SELECT * FROM brand WHERE " + Brand.ID + "='" + id
						+ "'", null);
		if (c.moveToFirst()) {
			brand = new BrandLocal();
			brand.id = id;
			brand.logo = c.getString(c.getColumnIndex(Brand.LOGO));
			brand.name = c.getString(c.getColumnIndex(Brand.NAME));
		}
		c.close();
		return brand;
	}

	@Override
	public void save(Brand brand) {
		ContentValues values = new ContentValues();
		values.put(Brand.ID, brand.id);
		values.put(Brand.LOGO, brand.logo);
		values.put(Brand.NAME, brand.name);
		synchronized (PercentApplication.localDB) {
			PercentApplication.localDB.insertWithOnConflict(Brand.TABLE, null,
					values, SQLiteDatabase.CONFLICT_REPLACE);
		}
	}

	@Override
	public List<Brand> findByMap(Map<String, String> map) {
		String value = null;
		Brand brand = null;
		final List<String> columns = Arrays.asList(Brand.COLUMNS);
		final StringBuffer selection = new StringBuffer();
		List<Brand> list = null;
		for (String key : map.keySet()) {
			value = map.get(key);
			if (columns.contains(key) && value != null) {
				selection.append(key + "='" + value + "' AND ");
				value = null;
			}
		}
		selection.append("'1'='1'");
		Cursor c = PercentApplication.localDB.rawQuery(
				"SELECT * FROM brand WHERE " + selection.toString(), null);
		list = new ArrayList<Brand>(c.getCount());
		while (c.moveToFirst()) {
			brand = new BrandLocal();
			brand.id = c.getLong(c.getColumnIndex(Brand.ID));
			brand.logo = c.getString(c.getColumnIndex(Brand.LOGO));
			brand.name = c.getString(c.getColumnIndex(Brand.NAME));
			list.add(brand);
		}
		c.close();
		return list;
	}

}
